'use strict';
const db = uniCloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    // 获取请求参数
    const { id } = event;
    const { OPENID } = context;
    
    // 验证请求参数
    if (!id) {
      return {
        code: 400,
        message: '壁纸ID不能为空'
      };
    }
    
    // 验证管理员权限
    const adminInfo = await db.collection('admin_users')
      .where({
        openid: OPENID,
        is_active: true
      })
      .field({
        _id: 1,
        username: 1,
        role: 1
      })
      .get();
    
    // if (adminInfo.data.length === 0) {
    //   return {
    //     code: 403,
    //     message: '您没有管理员权限'
    //   };
    // }
    
    // 执行事务查询
    const transaction = await db.startTransaction();
    
    try {
      // 查询壁纸详情
      const wallpaperInfo = await transaction.collection('wallpapers')
        .doc(id)
        .get();
      
      if (!wallpaperInfo.data || !wallpaperInfo.data[0]) {
        await transaction.rollback();
        return {
          code: 404,
          message: '壁纸不存在'
        };
      }
      
      const wallpaper = wallpaperInfo.data[0];
      let result = { ...wallpaper };
      
      // 获取分类信息
      if (wallpaper.categoryId) {
        const categoryInfo = await transaction.collection('categories')
          .doc(wallpaper.categoryId)
          .field({
            name: true,
            icon: true
          })
          .get();
        
        if (categoryInfo.data && categoryInfo.data[0]) {
          result.categoryName = categoryInfo.data[0].name;
          result.categoryIcon = categoryInfo.data[0].icon;
        }
      }
      
      // 确保标签字段是数组
      if (!Array.isArray(result.tags)) {
        result.tags = [];
      }
      
      // 规范化状态值返回格式
      if (result.status === 1) {
        result.status = 'approved';
      } else if (result.status === 0) {
        result.status = 'disabled';
      }
      
      // 记录操作日志
      await transaction.collection('admin_logs').add({
        admin_id: adminInfo.data[0]._id,
        admin_name: adminInfo.data[0].username,
        action: 'get_wallpaper_detail',
        target_id: id,
        target_title: result.title,
        create_time: Date.now()
      });
      
      // 提交事务
      await transaction.commit();
      
      return {
        code: 0,
        message: '获取壁纸详情成功',
        data: result
      };
      
    } catch (err) {
      // 回滚事务
      await transaction.rollback();
      console.error('查询壁纸详情事务失败:', err);
      
      // 尝试返回基本信息（非事务方式）
      try {
        const basicWallpaperInfo = await db.collection('wallpapers')
          .doc(id)
          .get();
        
        if (basicWallpaperInfo.data && basicWallpaperInfo.data[0]) {
          const basicResult = { ...basicWallpaperInfo.data[0] };
          // 规范化状态值返回格式
          if (basicResult.status === 1) {
            basicResult.status = 'approved';
          } else if (basicResult.status === 0) {
            basicResult.status = 'disabled';
          }
          return {
            code: 0,
            message: '获取壁纸基本信息成功（日志记录失败）',
            data: basicResult
          };
        }
      } catch (fallbackError) {
        console.error('回退查询也失败:', fallbackError);
      }
      
      throw err;
    }
    
  } catch (error) {
    console.error('获取壁纸详情失败:', error);
    return {
      code: 500,
      message: '获取壁纸详情失败，请稍后重试',
      error: error.message
    };
  }
};